package cn.sylinx.horm.spring.scan;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import cn.sylinx.horm.proxy.mapper.parse.NamespaceContainer;
import cn.sylinx.horm.proxy.mapper.registrar.MapperRegistrar;
import cn.sylinx.horm.util.GLog;

public class MapperScannerRegistrar implements ImportBeanDefinitionRegistrar {

	private List<String> packages;

	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
		
		GLog.info("Starting MapperScannerRegistrar at:{}", new Date());
		
		GLog.debug("Searching for Mapper ...");

		List<String> pkgs = getPackages();
		for (String pkg : pkgs) {
			MapperRegistrar.create().register(pkg);
		}

		List<Class<?>> maperClass = NamespaceContainer.getAllMapperClass();
		maperClass.forEach(c -> registerBean(c, registry));

	}

	private void registerBean(Class<?> maperClass, BeanDefinitionRegistry registry) {

		GLog.debug("注册 Mapper -->> {}", maperClass.getName());
		GenericBeanDefinition definition = new GenericBeanDefinition();
		definition.getConstructorArgumentValues().addGenericArgumentValue(maperClass.getName());
		definition.setBeanClass(MapperFactoryBean.class);
		definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
		registry.registerBeanDefinition(maperClass.getName(), definition);
	}

	public List<String> getPackages() {
		return packages;
	}

	public void setPackages(List<String> packages) {
		this.packages = packages;
	}
}